package com.dai.spec.gxk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dai.spec.common.constant.AvatarUrlConstants;
import com.dai.spec.common.constant.RoleConstants;
import com.dai.spec.common.core.domain.entity.SysUser;
import com.dai.spec.common.exception.base.BaseException;
import com.dai.spec.common.utils.SecurityUtils;
import com.dai.spec.common.utils.StringUtils;
import com.dai.spec.gxk.domain.Student;
import com.dai.spec.gxk.mapper.StudentMapper;
import com.dai.spec.gxk.service.StudentService;
import com.dai.spec.system.mapper.SysUserMapper;
import com.dai.spec.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 学生信息管理Service业务层处理
 *
 * @author daikl
 * @date 2024-02-29
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    private SysUserMapper sysUserMapper;

    private ISysUserService iSysUserService;

    private StudentMapper studentMapper;


    public StudentServiceImpl(SysUserMapper sysUserMapper, ISysUserService iSysUserService, StudentMapper studentMapper) {
        this.sysUserMapper = sysUserMapper;
        this.iSysUserService = iSysUserService;
        this.studentMapper = studentMapper;
    }

    /**
     * 查询学生信息管理列表
     *
     * @param student 学生信息管理
     * @return 学生信息管理
     */
    @Override
    public List<Student> queryList(Student student) {
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(student.getStudentNumber())) {
            queryWrapper.eq(Student::getStudentNumber, student.getStudentNumber());
        }
        if (StringUtils.isNotEmpty(student.getName())) {
            queryWrapper.like(Student::getName, student.getName());
        }

        return this.list(queryWrapper);
    }

    /**
     * 添加学生，给予学生权限
     *
     * @param student
     * @return
     */
    @Override
    @Transactional
    public int saveWithUser(Student student) {
        this.validateStudent(student);
        SysUser sysUser = buildSysUser(student);
        int rows = iSysUserService.insertUser(sysUser);
        Long userId = sysUser.getUserId();
        student.setUserId(userId);
        studentMapper.insert(student);
        return rows;
    }
    /**
     * 修改学生
     *
     * @param student
     * @return
     */
    @Override
    @Transactional
    public int updateWithUser(Student student) {
       this.validateStudent(student);
        Long userId = student.getUserId();
        this.checkUserId(userId);
        SysUser sysUser = iSysUserService.selectUserById(userId);
        this.buildUpdateSysUser(student, sysUser);
        int row = iSysUserService.updateUser(sysUser);
        studentMapper.updateById(student);
        return row;
    }

    @Override
    @Transactional
    public int removeByIdsWithUser(List<Long> ids) {
       if (StringUtils.isEmpty(ids)){
          throw new BaseException("ids为空！");
       }
        ArrayList<Long> userIds = new ArrayList<>();
        for (Long id : ids) {
            LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Student::getId,id);
            Student student = studentMapper.selectOne(queryWrapper);
            String studentNumber = student.getStudentNumber();
            SysUser sysUser = iSysUserService.selectUserByUserName(studentNumber);
            userIds.add(sysUser.getUserId());
        }
        Long[] idsArray = toIdsArray(userIds);
        int rows = iSysUserService.deleteUserByIds( idsArray);
        studentMapper.deleteBatchIds(ids);
        return rows;
    }

    private static Long[] toIdsArray(List<Long> ids) {
        Long[] userIds = new Long[ids.size()];
        for (int i = 0; i < ids.size(); i++) {
            userIds[i] = ids.get(i);
        }
        return userIds;
    }


    private static void checkUserId(Long userId) {
        if (null == userId){
           throw new BaseException("userId不能为空，该学生没有关联用户表！");
       }
    }

    private static void buildUpdateSysUser(Student student, SysUser sysUser) {
        String studentNumber = student.getStudentNumber();
        String studentName = student.getName();
        String phoneNumber = student.getPhoneNumber();
        String sex = student.getSex();
        sysUser.setUserName(studentNumber);
        sysUser.setNickName(studentName);
        sysUser.setPhonenumber(phoneNumber);
        sysUser.setSex(sex);
    }

    /**
     * 学生字段校验
     *
     * @param student
     */
    private  void validateStudent(Student student) {
        if (StringUtils.isEmpty(student.getStudentNumber())) {
            throw new BaseException("学生学号不能为空！");
        }
        if (StringUtils.isEmpty(student.getName())) {
            throw new BaseException("学生姓名不能为空！");
        }
        if (StringUtils.isEmpty(student.getPhoneNumber())) {
            throw new BaseException("学生电话号码不能为空！");
        }
        if (StringUtils.isEmpty(student.getSex())) {
            throw new BaseException("学生性别不能为空！");
        }
    }

    /**
     * 封装SysUser对象
     *
     * @param student
     * @return
     */
    private static SysUser buildSysUser(Student student) {
        String studentNumber = student.getStudentNumber();
        //姓名、性别、电话号码、头像
        String studentName = student.getName();
        String phoneNumber = student.getPhoneNumber();
        String sex = student.getSex();

        SysUser sysUser = new SysUser();
        //默认学号作为登录时的用户名
        sysUser.setUserName(studentNumber);
        //默认初始密码为学号
        String encryptPassword = SecurityUtils.encryptPassword(studentNumber);
        sysUser.setPassword(encryptPassword);
        sysUser.setNickName(studentName);
        sysUser.setPhonenumber(phoneNumber);
        sysUser.setSex(sex);
        //性别为女,设置默认头像
        if ("1".equals(sex)) {
            sysUser.setAvatar(AvatarUrlConstants.STUDENT_WOMAN_AVATAR);
        } else if ("0".equals(sex)) {
            sysUser.setAvatar(AvatarUrlConstants.STUDENT_MAN_AVATAR);
        }
        //设置权限
        sysUser.setRoleId(RoleConstants.STUDENT);
        sysUser.setRoleIds(Arrays.asList(RoleConstants.STUDENT).toArray(new Long[0]));
        return sysUser;
    }


//    /**
//     * 新增学生课程关联信息
//     *
//     * @param student 学生信息管理对象
//     */
//    public void insertStudentCourse(Student student) {
//        List<SelectedCourse> selectedCourseList = student.getSelectedCourseList();
//        Long id = student.getId();
//        if (StringUtils.isNotNull(selectedCourseList)) {
//            List<SelectedCourse> list = new ArrayList<SelectedCourse>();
//            for (SelectedCourse selectedCourse : selectedCourseList) {
//                selectedCourse.setStudentNumber(id);
//                list.add(selectedCourse);
//            }
//            if (list.size() > 0) {
////                studentMapper.batchStudentCourse(list);
//            }
//        }
//    }
}
